package com.hsgene.message.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.hsgene.message.persistence.MQRepository;
import com.hsgene.mq.*;
import com.hsgene.order.domain.billing.dto.BillingConfirmMQInfo;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

/**
 * 消息监听
 *
 * @author wxf
 * @date 2018/12/6 15:55
 **/
@Component
public class MQMessageListener implements MessageListener {

    /**
     * Log
     */
    private static Logger LOGGER = LogManager.getLogger(MQMessageListener.class);
    /**
     * 录入申请Tag
     */
    @Value("${tag.apply}")
    private String applyTag;
    /**
     * 补充材料Tag
     */
    @Value("${tag.addMaterials}")
    private String addMaterialsTag;
    /**
     * dcw编号Tag
     */
    @Value("${tag.dcwNo}")
    private String dcwNoTag;
    /**
     * 审核积分Tag
     */
    @Value("${tag.verifyIntegral}")
    private String verifyIntegralTag;
    /**
     * 积分发放完成更新状态Tag
     */
    @Value("${tag.grantIntegral}")
    private String grantIntegralTag;
    /**
     * 发票确认回调tag
     */
    @Value("${tag.invoiceTag}")
    private String invoiceTag;

    /**
     * 地服用户信息同步tag
     */
    @Value("${tag.userInfoTag}")
    private String userInfoTag;

    /**
     * dcw评分Tag
     */
    @Value("${tag.dcwPointsTag}")
    private String dcwPointsTag;

    @Resource
    private MQRepository mqRepository;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        try {
            Map<String, Object> content = (Map<String, Object>) JSON.parse(message.getBody());
            String tagKey = message.getTag();
            LOGGER.info("receive message tag is :" + tagKey + ",message content is :" + content);
            //根据tag类型操作不同业务
            //dcw编号，保存到基因检测订单,更新genetic_testing_order_dcw
            if (tagKey.equals(dcwNoTag)) {
                LOGGER.info("dcw update message...");
                DcwModel dcwModel = new DcwModel();
                BeanUtils.populate(dcwModel, content);
                mqRepository.upateDcwInfo(dcwModel);
                return Action.CommitMessage;
            }
            //积分发放完成,客户端修改积分状态,更新genetic_testing_order_addtion_a
            if (tagKey.equals(grantIntegralTag)) {
                LOGGER.info("积分发放完成,通知客户端修改积分状态消息...");
                IntegralModel integralModel = new IntegralModel();
                BeanUtils.populate(integralModel, content);
                mqRepository.upateOrderAddtionA(integralModel);
                return Action.CommitMessage;
            }
            // 附件不符，订单状态回退，genetic_testing_order_dcw表申请状态更新为：0、未申请
            if (tagKey.equals(addMaterialsTag)) {
                LOGGER.info("附件不符，订单dcw申请状态回退消息...");
                DcwBackInfo backInfo = new DcwBackInfo();
                BeanUtils.populate(backInfo, content);
                //申请状态修改为：2被拒绝
                mqRepository.upateDcwBackInfo(backInfo);
                //回退记录插入表中
                mqRepository.insertApplyBackRecord(backInfo);
                return Action.CommitMessage;
            }
            //开票确认回调刷新订单发票状态genetic_testing_order_invoice
            if (tagKey.equals(invoiceTag)) {
                LOGGER.info("开票确认回调刷新订单发票状态消息...");
                BillingConfirmMQInfo confirmMQInfo = new BillingConfirmMQInfo();
                BeanUtils.populate(confirmMQInfo, content);
                //更新订单发票状态
                mqRepository.updateOrderInvoice(confirmMQInfo);
                //更新订单状态为22:待寄送至地服
                mqRepository.updateOrder(confirmMQInfo.getOrderId());
                return Action.CommitMessage;
            }
            //用户信息同步
            if (tagKey.equals(userInfoTag)) {
                LOGGER.info("地服信息同步...");
                DifuUserInfo userInfo = new DifuUserInfo();
                BeanUtils.populate(userInfo, content);
                if (StringUtils.isEmpty(userInfo.getMobile())) {
                    userInfo.setMobile(userInfo.getPhone());
                }
                //用户信息插入
                mqRepository.inserUserInfo(userInfo);
                Boolean flag = mqRepository.queryUserGroundServantInfo(userInfo.getId());
                if (flag == null || !flag) {
                    mqRepository.inserUserGroundServantInfo(userInfo);
                } else {
                    mqRepository.updateUserGroundServantInfo(userInfo);
                }
                return Action.CommitMessage;
            }
            // dcw评分Tag，有评分表示审核通过
            if (tagKey.equals(dcwPointsTag)) {
                LOGGER.info("DCW审核通过，获取DCW评分...");
                DcwPointsModel model = new DcwPointsModel();
                BeanUtils.copyProperties(model, content);
                LOGGER.info("DCW评分信息：{}", model);
                mqRepository.updateDcwPoints(model);
                return Action.CommitMessage;
            }
            return Action.ReconsumeLater;
        } catch (Exception e) {
            LOGGER.error(message.getTag() + " message is error...", e);
            return Action.ReconsumeLater;
        }
    }
}
